// ignore_for_file: prefer_typing_uninitialized_variables, use_build_context_synchronously
import 'dart:isolate';
import 'dart:ui';
import 'package:bot_toast/bot_toast.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:preload_page_view/preload_page_view.dart';
import 'package:provider/provider.dart';
import 'package:wallpaper_app/components/AlertDialog/circular_progress.dart';
import 'package:wallpaper_app/components/AlertDialog/my_loading.dart';
import 'package:wallpaper_app/components/windows/window_title_bar.dart';
import 'package:wallpaper_app/db/love_database.dart';
import 'package:wallpaper_app/tools/custom_image_cache.dart';
import 'package:wallpaper_app/tools/save_file.dart';
import 'package:wallpaper_app/tools/wallpaper_service.dart';

// ignore: must_be_immutable
class ImageView extends StatefulWidget {
  final List images;
  int selectedIndex;
  final VoidCallback resetGetdata;
  bool isMobile;
  ImageView({
    super.key,
    required this.images,
    required this.selectedIndex,
    required this.resetGetdata,
    this.isMobile = false,
  });

  @override
  State<ImageView> createState() => _ImageViewState();
}

class _ImageViewState extends State<ImageView>
    with SingleTickerProviderStateMixin {
  bool isLove = false;
  late PreloadPageController _pageController;
  late AnimationController _animationController;
  late Animation<double> _fadeAnimation;
  bool _controlsVisible = true;
  var loadingBot;
  int activeIndex = 0;

  // 监听 Isolate 发送的消息
  void setupReceivePort() {
    // 先移除可能存在的旧端口映射，避免重复注册
    if (IsolateNameServer.lookupPortByName('mainPort') != null) {
      IsolateNameServer.removePortNameMapping('mainPort');
    }

    final receivePort = ReceivePort();
    IsolateNameServer.registerPortWithName(receivePort.sendPort, 'mainPort');

    receivePort.listen((message) {
      if (message is Map) {
        final messageContent = message['message'];
        BotToast.showText(
          text: messageContent,
          align: Alignment.center,
        );
      }
      // 关闭遮罩层
      if (loadingBot != null) {
        loadingBot();
      }
    });
  }

  void setWallPaper(String url) async {
    try {
      loadingBot = BotToast.showCustomLoading(
          backgroundColor: const Color.fromARGB(100, 4, 4, 4),
          toastBuilder: (cancel) {
            return Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                MyLoading(type: 2),
                SizedBox(height: 10),
                Text(
                  '正在设置中...',
                  style: TextStyle(color: Colors.white, fontSize: 13),
                ),
              ],
            );
          });
      // 先读取缓存中的图片 存在缓存则直接返回
      final cacheFile = await CustomCacheManager().getSingleFile(url);
      // 先从零时缓存目录保存到本地
      String newPath = await SaveFile.saveFileWallPaper(cacheFile.path);
      await WallpaperService.setWallpaperInIsolate(newPath);
    } catch (e) {
      BotToast.showText(
        text: '设置壁纸时出错',
        contentColor: Colors.red,
      );
      loadingBot();
    }
  }

  void isLoveGet() async {
    bool res = await context.read<LoveDatabase>().isLove(
          widget.isMobile
              ? widget.images[activeIndex].largePath
              : widget.images[activeIndex].smallPath,
        );
    setState(() {
      isLove = res;
    });
  }

  void shareImage() async {
    // 分享图片 复制图片地址到剪贴板
    Clipboard.setData(
        ClipboardData(text: widget.images[activeIndex].largePath));
    BotToast.showText(text: '地址复制成功');
  }

  void changeLove() {
    setState(() {
      isLove = !isLove;
    });

    context.read<LoveDatabase>().addLove(
        widget.isMobile
            ? widget.images[activeIndex].largePath
            : widget.images[activeIndex].smallPath,
        widget.images[activeIndex].largePath,
        widget.images[activeIndex].tags,
        'image',
        'horizontal'
        // width! > height! ? 'horizontal' : 'vertical',
        );
    widget.resetGetdata();
  }

  @override
  void initState() {
    setupReceivePort();
    setState(() {
      activeIndex = widget.selectedIndex;
    });
    super.initState();
    _pageController = PreloadPageController(initialPage: widget.selectedIndex);

    // 初始化动画控制器
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 300),
      vsync: this,
    );

    _fadeAnimation = Tween<double>(begin: 1.0, end: 0.0).animate(
      CurvedAnimation(parent: _animationController, curve: Curves.easeInOut),
    );
    isLoveGet();
  }

  @override
  void dispose() {
    _pageController.dispose();
    _animationController.dispose();
    // 确保在页面销毁时移除端口映射
    if (IsolateNameServer.lookupPortByName('mainPort') != null) {
      IsolateNameServer.removePortNameMapping('mainPort');
    }
    super.dispose();
  }

  void _toggleControls() {
    setState(() {
      _controlsVisible = !_controlsVisible;
      if (_controlsVisible) {
        _animationController.reverse();
      } else {
        _animationController.forward();
      }
    });
  }

  void _nextImage() {
    if (widget.selectedIndex < widget.images.length - 1) {
      _pageController.nextPage(
        duration: const Duration(milliseconds: 400),
        curve: Curves.easeInOut,
      );
    }
  }

  void _previousImage() {
    if (activeIndex > 0) {
      _pageController.previousPage(
        duration: const Duration(milliseconds: 400),
        curve: Curves.easeInOut,
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context).colorScheme;
    return Scaffold(
      backgroundColor: Colors.black,
      body: Column(
        children: [
          WindowTitleBar(isBack: true),
          Expanded(
            child: GestureDetector(
              onTap: _toggleControls,
              child: Stack(
                children: [
                  // 修复模糊效果的背景
                  SizedBox.expand(
                    child: ClipRect(
                      child: Container(
                        decoration: BoxDecoration(
                          image: DecorationImage(
                            image: CachedNetworkImageProvider(
                              widget.images[widget.selectedIndex].smallPath,
                            ),
                            fit: BoxFit.cover, // 改为cover以填满整个区域
                          ),
                        ),
                        child: BackdropFilter(
                          filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
                          child: Container(
                            color: Colors.black.withOpacity(0.2),
                          ),
                        ),
                      ),
                    ),
                  ),

                  // 图片内容
                  PreloadPageView.builder(
                    controller: _pageController,
                    scrollDirection: Axis.horizontal,
                    physics: const BouncingScrollPhysics(),
                    itemCount: widget.images.length,
                    itemBuilder: (context, index) {
                      return _buildImageView(widget.images[index].largePath);
                    },
                    onPageChanged: (index) {
                      setState(() {
                        widget.selectedIndex = index;
                        activeIndex = index;
                        isLoveGet();
                      });
                    },
                  ),

                  // 底部控制栏 - 使用IgnorePointer根据_controlsVisible状态控制交互
                  Positioned(
                    bottom: 20,
                    left: 0,
                    right: 0,
                    child: IgnorePointer(
                      ignoring: !_controlsVisible,
                      child: FadeTransition(
                        opacity: _fadeAnimation,
                        child: Align(
                          alignment: Alignment.center,
                          child: Container(
                            padding: EdgeInsets.only(left: 10, right: 10),
                            decoration: BoxDecoration(
                              color: Colors.white.withOpacity(0.3),
                              borderRadius:
                                  BorderRadius.all(Radius.circular(5)),
                            ),
                            child: Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                // 控制栏按钮保持不变...
                                Tooltip(
                                  message: '桌面壁纸',
                                  child: IconButton(
                                      color:
                                          theme.primary,
                                      onPressed: () {
                                        setWallPaper(widget
                                            .images[activeIndex].largePath);
                                      },
                                      icon: Icon(
                                        Icons.laptop_mac,
                                        color: Colors.white,
                                      )),
                                ),
                                SizedBox(width: 20),
                                Tooltip(
                                  message: '保存壁纸',
                                  child: IconButton(
                                      color:
                                          theme.primary,
                                      onPressed: () async {
                                        final cacheFile =
                                            await CustomCacheManager()
                                                .getSingleFile(widget
                                                    .images[activeIndex]
                                                    .largePath);
                                        await SaveFile.saveImageFile(
                                            cacheFile.path);
                                        BotToast.showText(text: '保存成功');
                                      },
                                      icon: Icon(
                                        Icons.move_to_inbox,
                                        color: Colors.white,
                                      )),
                                ),
                                SizedBox(width: 20),
                                Tooltip(
                                  message: '收藏',
                                  child: IconButton(
                                      color:
                                          theme.primary,
                                      onPressed: changeLove,
                                      icon: Icon(
                                        Icons.favorite,
                                        color:
                                            isLove ? Colors.red : Colors.white,
                                      )),
                                ), // 使用 SizedBox 替代 Row 的 spacing 属性
                                SizedBox(width: 20),
                                Tooltip(
                                  message: '分享',
                                  child: IconButton(
                                      color:
                                          theme.primary,
                                      onPressed: shareImage,
                                      icon: Icon(
                                        Icons.share,
                                        color: Colors.white,
                                      )),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),

                  // 左侧切换按钮
                  if (widget.selectedIndex > 0)
                    Positioned(
                      left: 10,
                      top: 0,
                      bottom: 0,
                      child: IgnorePointer(
                        ignoring: !_controlsVisible,
                        child: FadeTransition(
                          opacity: _fadeAnimation,
                          child: Align(
                            alignment: Alignment.center,
                            child: Material(
                              borderRadius: BorderRadius.circular(25),
                              clipBehavior: Clip.antiAlias,
                              color: const Color.fromARGB(56, 158, 158, 158),
                              child: InkWell(
                                onTap: _previousImage,
                                child: Icon(
                                  Icons.chevron_left,
                                  size: 40,
                                  color: Colors.white,
                                ),
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),

                  // 右侧切换按钮
                  if (widget.selectedIndex < widget.images.length - 1)
                    Positioned(
                      right: 10,
                      top: 0,
                      bottom: 0,
                      child: IgnorePointer(
                        ignoring: !_controlsVisible,
                        child: FadeTransition(
                          opacity: _fadeAnimation,
                          child: Center(
                            child: Material(
                              borderRadius: BorderRadius.circular(25),
                              clipBehavior: Clip.antiAlias,
                              color: const Color.fromARGB(56, 158, 158, 158),
                              child: InkWell(
                                onTap: _nextImage,
                                child: Icon(
                                  Icons.chevron_right,
                                  size: 40,
                                  color: Colors.white,
                                ),
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildImageView(String imagePath) {
    // 确保缓存目录存在
    CustomCacheManager.ensureCacheDirExists();

    // 使用ValueNotifier来保持加载状态，确保状态在widget重建时保持
    ValueNotifier<bool> fullyLoaded = ValueNotifier<bool>(false);

    return InteractiveViewer(
      minScale: 0.5,
      maxScale: 4.0,
      child: CachedNetworkImage(
        width: double.infinity,
        height: double.infinity,
        imageUrl: imagePath,
        fit: BoxFit.contain,
        cacheManager: CustomCacheManager(),
        // 移除淡入动画，避免与进度条显示冲突
        fadeInDuration: Duration.zero,
        progressIndicatorBuilder: (context, url, progress) {
          // 如果进度达到100%，立即标记为已完成
          if (progress.progress == 1.0 && !fullyLoaded.value) {
            fullyLoaded.value = true;
          }

          // 使用ValueListenableBuilder监听加载状态变化
          return ValueListenableBuilder<bool>(
              valueListenable: fullyLoaded,
              builder: (context, isLoaded, _) {
                // 如果已加载完成，立即隐藏进度条
                if (isLoaded) {
                  return const SizedBox.shrink();
                }
                if (progress.progress == 0 || progress.progress == null) {
                  return Center(
                    child: MyLoading(),
                  );
                } else {
                  return Center(
                    child: CircularProgress(
                      value: progress.progress ?? 0,
                      showBorder: true,
                    ),
                  );
                }
              });
        },
        errorWidget: (context, url, error) => Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(Icons.error, color: Colors.red, size: 40),
              const SizedBox(height: 8),
              Text(
                '加载失败',
                style: TextStyle(color: Colors.red),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
